package com.rex.saas.utils;

import cn.hutool.json.JSONArray;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @ClassName JwtUtils
 * @Description:
 * @Author: zhusiyu
 * @CreateDate: 2024/12/13 10:05	//创建时间
 */
public class JwtUtils {
    /**
     * @param token
     * @return
     */
    public static String getTenantId(String token) {
        Map tokenPayload = JwtUtils.getPayload(token);
        return (String) tokenPayload.get("tenantId");
    }

    public static List<String> getRole(String token) {
        List<String> roles = new ArrayList<>();
        Map tokenPayload = JwtUtils.getPayload(token);
        JSONArray scopes = (JSONArray) tokenPayload.get("scopes");
        for (Object scope : scopes){
            roles.add((String) scope);
        }
        return roles;
    }

    /**
     * @param token
     * @return
     */
    public static String getCustomerId(String token) {
        Map tokenPayload = JwtUtils.getPayload(token);
        return (String) tokenPayload.get("customerId");
    }

    /**
     * @param token
     * @return
     */
    public static String getUserId(String token) {
        Map tokenPayload = JwtUtils.getPayload(token);
        return (String) tokenPayload.get("userId");
    }

    /**
     * 获取JWT Token的payLoad
     *
     * @param token
     * @return
     */
    public static Map getPayload(String token) {
        JWT jwt = JWTUtil.parseToken(token);
        JWTPayload payload = jwt.getPayload();
        return payload.getClaimsJson();
    }

    /**
     * 校验Token是否合法和过期
     * @param token
     * @param tokenKey
     * @return
     */
    public static boolean verifyToken(String token, String tokenKey) {
        JWT jwt = JWTUtil.parseToken(token);
        jwt.setKey(tokenKey.getBytes(StandardCharsets.UTF_8));
        // 过期时间单位：s ,距离过期时间少于600秒，则为false
        return JWTUtil.verify(token, tokenKey.getBytes(StandardCharsets.UTF_8)) && jwt.validate(600);
    }

}
